package com.exmaple.springcloud.controller;

import com.exmaple.springcloud.domain.R;
import com.exmaple.springcloud.entity.Pay;
import com.exmaple.springcloud.entity.PayDTO;
import com.exmaple.springcloud.enums.ReturnCodeEnum;
import com.exmaple.springcloud.service.PayService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/pay")
public class PayController {
    @Autowired
    PayService payService;

    @PostMapping(value = "/add")
    public R<String> addPay(@RequestBody Pay pay){
        System.out.println(pay.toString());
        int i = payService.addPay(pay);
        return R.ok("成功插入记录，返回值："+i);
        //return "成功插入记录，返回值："+i;
    }

    @GetMapping(value = "/del/{id}")
    public R deletePay(@PathVariable("id") Integer id) {
        int i = payService.deletePay(id);
        if (i==1){
            return R.ok("删除成功");
        }else {
            return R.fail(ReturnCodeEnum.RC88.getCode(),"删除失败");
        }

        //return payService.deletePay(id);
    }

    @PostMapping(value = "/update")
    public R<String> updatePay(@RequestBody PayDTO payDTO){
        Pay pay = new Pay();
        BeanUtils.copyProperties(payDTO, pay);

        int i = payService.updatePay(pay);
        //return "成功修改记录，返回值："+i;
        return R.ok("成功修改记录，返回值：+i");
    }


    @GetMapping(value = "/get/{id}")
    public R<Pay> getPayById(@PathVariable("id") Integer id){
        if(id == -1) throw new RuntimeException("id不能为负数");
        try {
            //模拟超时。服务提供方业务处理,为了测试feign的超时时间控制，设置线程睡眠62秒
            Thread.sleep(62*1000);
        }catch (Exception e){
            e.printStackTrace();
        }
        Pay payById = payService.getPayById(id);
        return R.ok(payById);
    }


    @GetMapping("/getPayAllList")
    public R<List<Pay>> getPayAllList(){
        List<Pay> payAllList = payService.getPayAllList();
        return R.ok(payAllList);
    }


    @Value("${server.port}")
    private String port;

    @GetMapping(value = "/get/info")
    private String getInfoByConsul(@Value("${payment.info}") String paymentInfo)
    {
        return "paymentInfo: "+paymentInfo+"\t"+"port: "+port;
    }


    @Value("${spring.application.name}")
    private String serviceName;

    @GetMapping(value = "/get/serviceInfo")
    public String getServiceInfo()
    {
        return "ServiceName:  "+serviceName+"\t"+" ,port: "+port;
    }
}
